package com.edee.bigday.ware.listener;

import com.edee.bigday.ware.service.WareSkuService;
import com.edee.common.to.mq.OrderTo;
import com.edee.common.to.mq.StockLockedTo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息~~~");
        try {
            // 判断消息是第一次投递过来，还是被重新投递过来的（可以结合对上次消费结果进行综合判断是否要重新消费）：
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //有任何异常，拒绝消息，重新归队：
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo,Message message, Channel channel) throws IOException {
        System.out.println("订单关闭，准备解锁库存......");
        try {
            wareSkuService.unlockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //有任何异常，拒绝消息，重新归队：
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
